package com.hhd.pdf.variable;

import com.hhd.pdf.CommonUtils;
import lombok.Getter;
import lombok.Setter;

import java.math.BigDecimal;

@Getter
@Setter
public class ParsedFormula implements Formula {
    private final String formulaText;
    private String[] path;
    private String formulaValue;
    private VariablePath variablePath;

    public ParsedFormula(String formulaText) {
        this.formulaText = getResolvedFormulaText(formulaText);
    }

    public static ParsedFormula formula(String formula) {
        ParsedFormula res = new ParsedFormula(formula);
        res.parse();
        return res;
    }

    private void parse() {
        this.path = formulaText.split("\\.");
    }

    private String getResolvedFormulaText(String formulaText) {
        String temp = formulaText.replaceAll("\\{", "");
        temp = temp.replaceAll("\\}", "");
        return temp.trim();
    }

    public String getLastPath() {
        return path[path.length - 1];
    }

    public String getFormulaValue() {
        if (CommonUtils.isEmpty(formulaValue)) return "";
        return formulaValue;
    }

    public VariablePath createVariableFormula() {
        if (!CommonUtils.isEmpty(variablePath)) return variablePath;
        return variablePath = VariablePath.formula(this.formulaText);
    }

    @Override
    public void setFormulaValue(Object value) {
        if (!CommonUtils.isEmpty(value)) {
            if (value instanceof BigDecimal) {
                BigDecimal decimal = (BigDecimal) value;
                value = decimal.setScale(2);
            }
            this.formulaValue = value.toString();
        }
    }
}
